import React from "react";
import SearchHeader from "./component/SearchHeader";
import TheTable from "@/components/TheTable";
import TheButton from "@/components/TheButton";
import "../style/style.less";
import ThePagination from "../../../components/ThePagination";
import {
  apiGetGoodsInfoPage,
  apiGetGoodsInfoPutaway,
  apiGetGoodsInfoRecommend,
  apiGetGoodsInfoList,
} from "@/request/mallManagement";
import TheImage from "@/components/TheImage";
import { Space } from "antd";
import { exportSheetTable } from "@/utils/exportTable";
import TheQueryForm from "../../../components/TheQueryForm";
import TheTableExtend from "@/components/TheTableExtend";
import store from "@/store/store";
import { apiGetGoodsClassifyList } from "@/request/mallManagement";
import { getDateTime3 } from "@/utils/getDate";
import _ from "lodash";

let options = [];
class List extends React.Component {
  constructor(props) {
    super(props);
    this.queryFormRef = React.createRef();

    this.state = {
      down_loading: false,

      columns: [
        {
          title: "商品ID",
          dataIndex: "goodsId",
          key: "goodsId",
        },
        {
          title: "商品名称",
          dataIndex: "goodsName",
          key: "goodsName",
          render: (text, record) => {
            return (
              <div
                style={{
                  width: 200,
                  overflow: "hidden",
                  whiteSpace: "nowrap",
                  textOverflow: "ellipsis",
                }}
              >
                {record.goodsName}
              </div>
            );
          },
        },
        {
          title: "商品图片",
          dataIndex: "goodsShowImages",
          key: "goodsShowImages",
          render: (text) => {
            let arr = text.split(",");
            return (
              <Space>
                {arr.map((v) => {
                  return <TheImage src={v} width={80} height={80} />;
                })}
              </Space>
            );
          },
        },
        {
          title: "所属类目",
          dataIndex: "goodsClassifyName",
          key: "goodsClassifyName",
        },
        {
          title: "商品原价",
          dataIndex: "originalPrice",
          key: "originalPrice",
          render: (text) => {
            return <React.$Price price={text || 0} />;
          },
        },
        {
          title: "商品现价",
          dataIndex: "currentPrice",
          key: "currentPrice",
          render: (text) => {
            return <React.$Price price={text || 0} />;
          },
        },
        {
          title: "所属商家",
          dataIndex: "storeName",
          key: "storeName",
        },
        {
          title: "申请时间",
          dataIndex: "createTime",
          key: "createTime",
        },
        {
          title: "上次操作时间",
          dataIndex: "lastUpdateTime",
          key: "lastUpdateTime",
          render: (text, record) => {
            return record.lastUpdateTime ? record.lastUpdateTime : "/";
          },
        },
        {
          title: "操作人",
          dataIndex: "userName",
          key: "userName",
          render: (text, record) => {
            return record.userName ? record.userName : "/";
          },
        },
        {
          title: "状态",
          dataIndex: "goodsStatus",
          key: "goodsStatus",
          render: (text, render) => {
            let label = "";
            switch (render.goodsStatus) {
              case "Y":
                label = "上架";
                break;
              case "N":
                label = "下架";
                break;
              case "G":
                label = "管理员下架";
                break;
              default:
                label = "字段值错误";
            }
            return label;
          },
        },
        {
          title: "推荐",
          dataIndex: "recommendStatus",
          key: "recommendStatus",
          render: (text, render) => {
            let label = "";
            switch (render.recommendStatus) {
              case "Y":
                label = "是";
                break;
              case "N":
                label = "否";
                break;
              default:
                label = "字段值错误";
            }
            return label;
          },
        },
        {
          title: "操作",
          fixed: "right",
          width: 300,
          render: (text, render) => {
            return (
              <div>
                <TheButton
                  haspermi={["mall:list:detail"]}
                  onClick={() => this.goDetail(render.goodsId)}
                >
                  商品详情
                </TheButton>
                <TheButton
                  haspermi={["mall:list:evaluate"]}
                  onClick={() =>
                    this.goEvaluate(
                      render.goodsId,
                      render.storeName,
                      render.storeId
                    )
                  }
                >
                  商品评价
                </TheButton>
                {(render.goodsStatus === "N" || render.goodsStatus === "G") && (
                  <TheButton
                    haspermi={["mall:list:onShelf"]}
                    onClick={() => this.putShelf(render.goodsId, "Y")}
                  >
                    上架
                  </TheButton>
                )}
                {render.goodsStatus === "Y" && (
                  <TheButton
                    haspermi={["mall:list:onShelf"]}
                    onClick={() => this.offShelf(render.goodsId, "G")}
                  >
                    下架
                  </TheButton>
                )}
                {render.recommendStatus === "N" && (
                  <TheButton
                    haspermi={["mall:list:recommend"]}
                    onClick={() => this.putRecommend(render.goodsId, "Y")}
                  >
                    推荐
                  </TheButton>
                )}
                {render.recommendStatus === "Y" && (
                  <TheButton
                    haspermi={["mall:list:recommend"]}
                    onClick={() => this.offRecommend(render.goodsId, "N")}
                  >
                    不推荐
                  </TheButton>
                )}
              </div>
            );
          },
        },
      ],
      dataSource: [],
      pageData: {
        pageNo: 1,
        pageSize: 10,
      },
      total: 0,
      searchValue: {},
      newColumns: [],
      form_show: true,
      searchOption: [
        {
          field: "goodsName",
          label: "商品名称",
          placeholder: "商品名称",
          required: false,
          rules: [],
          type: "Input",
          defaultValue: "",
        },
        {
          field: "goodsId",
          label: "商品ID",
          placeholder: "商品ID",
          required: false,
          rules: [],
          type: "Input",
          options: [],
          defaultValue: "",
        },
        {
          field: "goodsStatus",
          label: "上架状态",
          placeholder: "上架状态",
          required: false,
          rules: [],
          type: "Select",
          options: [
            { value: "Y", label: "上架" },
            { value: "N", label: "下架" },
            { value: "G", label: "管理员下架" },
          ],
          defaultValue: "",
        },
        {
          field: "classifyId",
          label: "所属类目",
          placeholder: "所属类目",
          required: false,
          rules: [],
          type: "Select",
          txt: "goodsClassifyName",
          value: "goodsClassifyId",
          options: [],
          api: apiGetGoodsClassifyList,
          params: { level: 2 },
          defaultValue: "",
        },
        {
          field: "time",
          label: "申请时间",
          placeholder: "",
          required: false,
          rules: [],
          type: "RangePicker",
          defaultValue: "",
        },
      ],
      queryForm: {},
    };
  }
  async componentDidMount() {
    this.onColumnsFilter(this.state.columns);
    let searchParams = store.getState().searchValue;
    let { pageNo, pageSize, queryForm, pathName } = searchParams;
    if (searchParams && pageNo && pathName == "mallList") {
      this.setState(
        {
          queryForm,
          pageData: {
            pageNo: pageNo,
            pageSize: pageSize,
          },
        },
        () => {
          this.queryFormRef.onSetDefault({
            ...queryForm,
          });
          this.getData();
        }
      );
    } else {
      this.getData();
    }
  }
  getData = async (values) => {
    let { pageNo, pageSize } = this.state.pageData;
    if (values && !_.isEmpty(values.time)) {
      values.createTimeStart = getDateTime3(values.time[0]);
      values.createTimeEnd = getDateTime3(values.time[1]);
    }
    this.setState(
      {
        queryForm: values === undefined ? this.state.queryForm : { ...values },
      },
      async () => {
        let { time, ...form } = { ...this.state.queryForm };
        const params = {
          pageNo,
          pageSize,
          queryForm: { ...form, time },
        };
        store.dispatch({
          type: "SaveSearchValues",
          data: {
            pathName: "mallList",
            ...params,
          },
        });
        let res = await apiGetGoodsInfoPage({
          pageNo,
          pageSize,
          ...form,
          reviewStatus: "T",
        });
        if (res.code === 0 && res.data) {
          this.setState({
            dataSource: res.data,
            pageData: { pageNo: res.pageNo, pageSize: res.pageSize },
            total: res.totalCount,
          });
        }
      }
    );
  };

  getValue = (value) => {
    this.setState(
      { searchValue: value, pageData: { pageNo: 1, pageSize: 10 } },
      () => {
        this.getData();
      }
    );
  };
  goDetail = (goodsId) => {
    this.props.history.push(`/mall/list/detail/${goodsId}`);
  };
  goEvaluate = (goodsId, storeName, storeId) => {
    this.props.history.push(
      `/mall/list/evaluate/${goodsId}/${encodeURIComponent(
        storeName
      )}/${storeId}`
    );
  };
  pageChange = (pageNo, pageSize) => {
    this.setState(
      {
        pageData: {
          pageNo,
          pageSize,
        },
      },
      () => {
        this.getData();
      }
    );
  };
  delConfirm = () => {
    React.$confirm({
      title: "您确认删除此条商品吗?",
      onOk: async () => { },
    });
  };
  offShelf = (goodsId, goodsStatus) => {
    React.$confirm({
      title: "您确定下架该商品吗？",
      onOk: async () => {
        await apiGetGoodsInfoPutaway({ goodsId, goodsStatus });
        await this.getData();
      },
    });
  };
  putShelf = (goodsId, goodsStatus) => {
    React.$confirm({
      title: "您确定上架该商品吗？",
      onOk: async () => {
        await apiGetGoodsInfoPutaway({ goodsId, goodsStatus });
        await this.getData();
      },
    });
  };
  offRecommend = (goodsId, recommendStatus) => {
    React.$confirm({
      title: "您确定取消推荐该商品吗？",
      onOk: async () => {
        await apiGetGoodsInfoRecommend({ goodsId, recommendStatus });
        await this.getData();
      },
    });
  };
  putRecommend = (goodsId, recommendStatus) => {
    React.$confirm({
      title: "您确定推荐该商品吗？",
      onOk: async () => {
        await apiGetGoodsInfoRecommend({ goodsId, recommendStatus });
        await this.getData();
      },
    });
  };
  //表格导出
  async toExportTable() {
    this.setState({ down_loading: true });
    await apiGetGoodsInfoList({ ...this.state.queryForm, reviewStatus: "T" })
      .then((res) => {
        if (res.code === 0 && res.data.length > 0) {
          let tH_data = [
            {
              title: "商城商品列表",
              prop: "",
              children: [
                { prop: 'goodsId', title: '商品ID' },
                { prop: 'goodsName', title: '商品名称' },
                { prop: 'classifyName', title: '所属类目' },
                { prop: 'storeName', title: '所属商家' },
                { prop: 'createTime', title: '申请时间' },
                { prop: 'storeGoodsState', title: '商品上下架状态' },
                { prop: 'skuStatus', title: 'SKU状态' },
                { prop: 'materialId', title: '物料ID' },
                { prop: 'goodsKeyValue', title: '规格' },
                { prop: 'skuOriginalPrice', title: '原价', valueType: 'number' },
                { prop: 'skuCurrentPrice', title: '日常价', valueType: 'number' },
                { prop: 'skuStock', title: '库存', valueType: 'number' },
                { prop: 'waiteOutCount', title: '待出库存', valueType: 'number' },
                { prop: 'onSalesTIme', title: '商品最近一次上架时间' },
                { prop: 'lastActivityPrice', title: '最近一次活动价' },
                { prop: 'minActivityPrice', title: '近一年最低活动价' },
              ],
            },
          ];
          let tB_data = res.data.map((item) => {
            return {
              goodsId: item.goodsId,
              goodsName: item.goodsName,
              classifyName: item.classifyName,
              storeName: item.storeName,
              createTime: item.createTime,
              storeGoodsState: this.getGoodsStatus(item.storeGoodsState),
              skuStatus: this.getGoodsStatus(item.skuStatus),
              materialId: item.materialId,
              goodsKeyValue: item.goodsKeyValue,
              skuOriginalPrice: (item.skuOriginalPrice / 100).toFixed(2),
              skuCurrentPrice: (item.skuCurrentPrice / 100).toFixed(2),
              skuStock: item.skuStock,
              waiteOutCount: item.waiteOutCount,
              onSalesTIme: item.onSalesTIme !== null ? item.onSalesTIme : "/",
              lastActivityPrice: item.lastActivityPrice !== null ? (item.lastActivityPrice / 100).toFixed(2) : "/",
              minActivityPrice: item.minActivityPrice !== null ? (item.minActivityPrice / 100).toFixed(2) : "/"
            };
          });

          this.setState({ down_loading: false });
          exportSheetTable({
            fileName: "商城商品列表",
            tH_data: tH_data,
            tB_data: tB_data,
            isSheet: true,
            merge: true,
            mergeProp: [
              "goodsId",
              "goodsName",
              "classifyName",
              "storeName",
              "createTime",
              "goodsStatus",
              "recommendStatus",
              "storeGoodsState"
            ],
          });
        } else {
          React.$message({
            type: "warning",
            content: "导出操作失败,请重试",
          });
          this.setState({ down_loading: false });
        }
      })
      .catch((err) => {
        React.$message({
          type: "warning",
          content: "导出操作失败,请重试",
        });
        this.setState({ down_loading: false });
      });
  }
  getRecommendStatus(text) {
    let label = "";
    switch (text) {
      case "Y":
        label = "是";
        break;
      case "N":
        label = "否";
        break;
      default:
        label = "字段值错误";
    }
    return label;
  }

  getGoodsStatus(text) {
    let label = "";
    switch (text) {
      case "Y":
        label = "上架";
        break;
      case "N":
        label = "下架";
        break;
      case "G":
        label = "管理员下架";
        break;
      default:
        label = "未同步";
    }
    return label;
  }
  onFinishSearch() {
    let values = this.formRef_search.current.getFieldsValue();
    this.setState(
      {
        code: values.code,
      },
      () => {
        this.pageChange(1, 10);
      }
    );
  }
  onReset() {
    this.setState(
      {
        queryForm: {},
      },
      () => {
        this.getData();
      }
    );
  }
  onColumnsFilter(value) {
    this.setState({
      newColumns: value,
    });
  }
  onFormSearch(values) {
    this.setState(
      {
        pageData: { pageNo: 1, pageSize: 10 },
      },
      () => {
        this.getData(values);
      }
    );
  }
  render() {
    const {
      columns,
      dataSource,
      pageData: { pageNo, pageSize },
      total,
      down_loading,
      form_show,
      searchOption,
      newColumns,
    } = this.state;
    return (
      <div className={"p-layout-box commodity-content"}>
        {/* <SearchHeader history={this.props.history} getValue={this.getValue} toExport={(e) => this.toExportTable(e)} loading={down_loading} /> */}
        <TheQueryForm
          ref={(ref) => (this.queryFormRef = ref)}
          show={form_show}
          option={searchOption}
          onReset={() => this.onReset()}
          onGetValues={(values) => this.onFormSearch(values)}
        ></TheQueryForm>
        <TheTableExtend
          columns={columns}
          onFormTrigger={() =>
            this.setState({ form_show: !this.state.form_show })
          }
          onTableRefresh={() => this.getData()}
          onColumnsFilter={(value) => this.onColumnsFilter(value)}
        >
          <TheButton
            size="middle"
            type="default"
            haspermi={["mall:list:exportGoodsBySku"]}
            onClick={() => this.toExportTable()}
            loading={this.props.loading}
          >
            导出商品
          </TheButton>
        </TheTableExtend>
        <div className="p-layout-content-pagination">
          <TheTable
            scroll={{ x: "max-content", y: "63vh" }}
            columns={newColumns}
            dataSource={dataSource}
          />
          <ThePagination
            pageNo={pageNo}
            pageSize={pageSize}
            total={total}
            pageChange={this.pageChange}
          />
        </div>
      </div>
    );
  }
}

export default List;
